package com.quyeying.utils.wx;

import com.quyeying.utils.httputils.HttpUtil;
import com.wechat.pay.contrib.apache.httpclient.auth.Verifier;
import com.wechat.pay.contrib.apache.httpclient.exception.ParseException;
import com.wechat.pay.contrib.apache.httpclient.exception.ValidationException;
import com.wechat.pay.contrib.apache.httpclient.notification.Notification;
import com.wechat.pay.contrib.apache.httpclient.notification.NotificationHandler;
import com.wechat.pay.contrib.apache.httpclient.notification.NotificationRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * PayUtil
 * @author shenkaixin
 */
@Slf4j
@Component
public class PayUtil {

    /**
     * 将通知参数转化为字符串
     * @param request
     * @return
     */
    public static String readData(HttpServletRequest request) {
        BufferedReader br = null;
        try {
            StringBuilder result = new StringBuilder();
            br = request.getReader();
            for (String line; (line = br.readLine()) != null; ) {
                if (result.length() > 0) {
                    result.append("\n");
                }
                result.append(line);
            }
            return result.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 验签解密报文
     */
    public static String signVerificationAndDecryption(String serialNumber, String nonce, String timestamp, String signature, String body) {
        Verifier verifier = HttpUtil.getVerifier();
        // 构建request，传入必要参数
        NotificationRequest request = new NotificationRequest.Builder().withSerialNumber(serialNumber)
                .withNonce(nonce)
                .withTimestamp(timestamp)
                .withSignature(signature)
                .withBody(body)
                .build();
        NotificationHandler handler = new NotificationHandler(verifier, WxPayConstans.API_V3KEY.getBytes(StandardCharsets.UTF_8));
        // 验签和解析请求体
        Notification notification = null;
        try {
            notification = handler.parse(request);
        } catch (ValidationException | ParseException e) {
            e.printStackTrace();
        }
        // 从notification中获取解密报文
        assert notification != null;
        log.info("解密报文："+notification.getDecryptData());
        return notification.getDecryptData();
    }
}
